package com.wise.wing.activity.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.methods.HttpUriRequest;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.DisplayUtil;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.picasso.Picasso;
import com.wise.wing.R;
import com.wise.wing.activity.logic.AdManager;
import com.wise.wing.bean.BaseData;
import com.wise.wing.bean.MapData;
import com.wise.wing.bean.RecommendAd;
import com.wise.wing.constant.Urls;

/**
 * 轮播广告碎片
 * 
 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
 * 
 * @author ZhuFan
 * @Date: 2015-3-13
 */
public class RecommendAdFragment extends Fragment implements OnClickListener, NListener<BaseData> {

	/**
	 * 广告轮播速度
	 */
	public static final int SCROLL_SPEED = 4000;

	/**
	 * 上下文
	 */
	private Activity mActivity;

	/**
	 * 页面控件
	 */
	private ViewPager vp_ads;
	private LinearLayout ll_dots;

	/**
	 * 存储广告信息
	 */
	private List<RecommendAd> ads;
	/**
	 * 存储广告图片
	 */
	private List<ImageView> images;
	/**
	 * 存储标识广告的圆点
	 */
	private List<View> dots;
	/**
	 * 广告数量
	 */
	private int count = 0;
	/**
	 * 用于自动轮播
	 */
	private Handler handler;
	private AdManager manager = new AdManager();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mActivity = getActivity();
		return inflater.inflate(R.layout.fragment_recommend_ad, null);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		findViews(view);
		init();
		addListeners();
		super.onViewCreated(view, savedInstanceState);
	}

	/**
	 * 初始化页面控件
	 * 
	 * @author ZhuFan
	 * @Package com.bm.jinzaitong.fragment
	 * @param view
	 * @return void
	 * @throws
	 * @Date 2015-3-13 上午10:06:21
	 */
	private void findViews(View view) {
		vp_ads = (ViewPager) view.findViewById(R.id.vp_ads);
		ll_dots = (LinearLayout) view.findViewById(R.id.ll_dots);
	}

	/**
	 * 初始化碎片
	 * 
	 * @author ZhuFan
	 * @Package com.bm.jinzaitong.fragment
	 * @return void
	 * @throws
	 * @Date 2015-3-13 上午10:06:34
	 */
	private void init() {
		handler = new Handler();
//		manager.getAds(this);
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("position", "2");
		httpUtils.send(HttpMethod.POST, Urls.GET_AD, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
//				Log.i("test", "请求成功");
				String result=arg0.result;
				try {
					JSONObject jsonObject =new JSONObject(result);
					String data = jsonObject.getString("data");
					String status=jsonObject.getString("status");
					MapData  mapData=JSON.parseObject(data, MapData.class);
//					Log.i("test", mapData.adverList.toString()+"");
					
					if ("1".equals(status)) {
						 ads = mapData.adverList;
						 if(ads == null || ads.size() <= 0)
						 return;
						 initViews();
						 initViewPager();
						 }
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	private void addListeners() {
	}

	/**
	 * 根据广告数量初始化图片以及小圆点
	 * 
	 * @author ZhuFan
	 * @Package com.bm.jinzaitong.fragment
	 * @return void
	 * @throws
	 * @Date 2015-3-13 上午10:06:54
	 */
	private void initViews() {
		count = ads.size();

		images = new ArrayList<ImageView>();
		dots = new ArrayList<View>();

		for (int i = 0; i < count; i++) {
			View view = buildChildView();
			ll_dots.addView(view);
			dots.add(view);
		}

		for (int i = 0; i < count; i++) {
			ImageView imageView = new ImageView(mActivity);
			imageView.setTag(ads.get(i));
			imageView.setOnClickListener(this);
			Picasso.with(mActivity).load(ads.get(i).img).into(imageView);
			imageView.setScaleType(ScaleType.FIT_XY);
			images.add(imageView);
		}
	}

	/**
	 * 初始化ViewPager
	 * 
	 * @author ZhuFan
	 * @Package com.bm.jinzaitong.fragment
	 * @return void
	 * @throws
	 * @Date 2015-3-13 上午10:07:20
	 */
	private void initViewPager() {
		vp_ads.setAdapter(new RecommendAdAdapter());
		vp_ads.setOnPageChangeListener(new RecommendAdPageChangedListener());
		vp_ads.setCurrentItem(0);
		dots.get(0).setBackgroundResource(R.drawable.dot_focused);
		handler.postDelayed(runnable, SCROLL_SPEED);
	}

	/**
	 * 生成小圆点
	 * 
	 * @author ZhuFan
	 * @Package com.bm.jinzaitong.fragment
	 * @return
	 * @return View
	 * @throws
	 * @Date 2015-3-13 上午10:07:30
	 */
	private View buildChildView() {
		View view = new View(mActivity);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DisplayUtil.dip2px(mActivity, 12), DisplayUtil.dip2px(mActivity, 3));
		view.setBackgroundResource(R.drawable.dot_normal);
		lp.setMargins(DisplayUtil.dip2px(mActivity, 1), 0, DisplayUtil.dip2px(mActivity, 1), 0);
		view.setLayoutParams(lp);

		return view;
	}

	/**
	 * 监听器
	 * 
	 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
	 * 
	 * @author ZhuFan
	 * @Date: 2015-3-13
	 */
	class RecommendAdPageChangedListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int arg0) {

			handler.removeCallbacks(runnable);

			int position = arg0 % count;
			for (int i = 0; i < count; i++) {
				if (i == position)
					dots.get(i).setBackgroundResource(R.drawable.dot_focused);
				else
					dots.get(i).setBackgroundResource(R.drawable.dot_normal);
			}

			handler.postDelayed(runnable, SCROLL_SPEED);
		}

	}

	/**
	 * 用于自动轮播的线程体
	 */
	private Runnable runnable = new Runnable() {

		@Override
		public void run() {

			int current = vp_ads.getCurrentItem();
			vp_ads.setCurrentItem(current + 1);

		}
	};

	/**
	 * 用于存储当页面被添加或删除时的position 当页面个数为3的时候, 无限轮播会出现bug, 必须在destroyItem中判断
	 * 当Math.abs(add - remove) == 0的时候不删除页面, 不然会出现空页面的情况
	 */
	private int add, remove = 0;

	/**
	 * 适配器
	 * 
	 * @Copyright Copyright © 2014 蓝色互动. All rights reserved.
	 * 
	 * @author ZhuFan
	 * @Date: 2015-3-13
	 */
	class RecommendAdAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return count < 3 ? count : Integer.MAX_VALUE;
		}

		@Override
		public Object instantiateItem(View container, int position) {
			int i = position % count;
			add = i;
			if (images.get(i).getParent() != null) {
				((ViewPager) images.get(i).getParent()).removeView(images.get(i));
			}
			((ViewPager) container).addView(images.get(i));
			return images.get(i);
		}

		@Override
		public void destroyItem(View arg0, int position, Object arg2) {
			int i = position % count;
			remove = i;
			if (count == 3 && Math.abs(add - remove) == 0)
				return;
			((ViewPager) arg0).removeView(images.get(i));
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

	}

	/**
	 * 页面暂停时取消轮播
	 */
	@Override
	public void onPause() {
		handler.removeCallbacks(runnable);
		super.onPause();
	}

	/**
	 * 页面恢复时注册轮播
	 */
	@Override
	public void onResume() {
		handler.postDelayed(runnable, SCROLL_SPEED);
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		RecommendAd ad = (RecommendAd) v.getTag();
		Intent intent = new Intent(mActivity, WebActivity.class);
		intent.putExtra("url", ad.linkSrc);
		startActivity(intent);
	}

	@Override
	public void onResponse(BaseData data) {
		Log.i("test", "测试");
		// if (data.status == 1) {
		// ads = data.data.adverList;
		// if(ads == null || ads.size() <= 0)
		// return;
		// initViews();
		// initViewPager();
		// }
	}

	@Override
	public void onErrResponse(VolleyError error) {
	}

	@Override
	public void onAllPageLoaded(int nowPage, int totalPage) {
	}

}
